<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SHOP_OWNER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="徽标" prop="logo">
        <UploadImg v-model="formData.logo" :limit="1" :is-show-tip="false"/>
      </el-form-item>
      <el-form-item label="简介" prop="introduction">
        <el-input v-model="formData.introduction" placeholder="请输入简介"/>
      </el-form-item>
      <el-form-item v-if="!formData.id" label="联系人姓名" prop="contactName">
        <el-input v-model="formData.contactName" placeholder="请输入联系人姓名"/>
      </el-form-item>
      <el-form-item v-if="!formData.id" label="联系电话" prop="contactMobile">
        <el-input v-model="formData.contactMobile" placeholder="请输入联系电话"/>
      </el-form-item>
      <el-form-item v-if="!formData.id" label="身份证号码" prop="ownerEidNo">
        <el-input v-model="formData.ownerEidNo" placeholder="请输入身份证号码"/>
      </el-form-item>
      <el-form-item v-if="!formData.id" label="身份证正面" prop="ownerEidFrontUrl">
        <UploadImg v-model="formData.ownerEidFrontUrl" :limit="1" :is-show-tip="false"/>
      </el-form-item>
      <el-form-item v-if="!formData.id" label="身份证反面" prop="ownerEidBackUrl">
        <UploadImg v-model="formData.ownerEidBackUrl" :limit="1" :is-show-tip="false"/>
      </el-form-item>
      <el-form-item v-if="!formData.id" label="营业执照" prop="businessLicenseUrl">
        <UploadImg v-model="formData.businessLicenseUrl" :limit="1" :is-show-tip="false"/>
      </el-form-item>
      <el-form-item label="主营类目" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择主营类目">
          <el-option
            v-for="(item,index) in categoryList"
            :key="index"
            :label="item.name"
            :value="item.id"
            :disabled="item.code !== 'food' && item.code !== 'mall'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="省市区县" prop="countyCode">
        <RegionPicker v-model="formData.countyCode"/>
      </el-form-item>
      <el-form-item v-if="formData.countyCode" label="详细地址" prop="detailAddress">
        <el-input v-model="formData.detailAddress" placeholder="请输入详细地址"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import * as AreaApi from '@/api/system/area'
import {defaultProps} from '@/utils/tree'
import {ShopInfoApi, CreateVO} from '@/api/mall/shop/info'
import {ShopCategoryApi} from "@/api/mall/shop/category";
import {RegionPicker} from '@/views/universal/region'

/** 店铺必要信息 表单 */
defineOptions({name: 'CreateForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  id: undefined,
  type: undefined,
  name: undefined,
  logo: undefined,
  introduction: undefined,
  contactName: undefined,
  contactMobile: undefined,
  ownerEidNo: undefined,
  ownerEidFrontUrl: undefined,
  ownerEidBackUrl: undefined,
  businessLicenseUrl: undefined,
  categoryId: undefined,
  countyCode: undefined,
  detailAddress: undefined,
  // userId: undefined
})
const formRules = reactive({
  type: [{required: true, message: '类型不能为空', trigger: 'change'}],
  name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  logo: [{required: true, message: '徽标不能为空', trigger: 'blur'}],
  contactName: [{required: true, message: '联系人姓名不能为空', trigger: 'blur'}],
  contactMobile: [
    {required: true, message: '联系电话不能为空', trigger: 'blur'},
    {pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  ownerEidNo: [
    {required: true, message: '身份证号码不能为空', trigger: 'blur'},
    {
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[Xx\d]$/,
      message: '请输入正确的身份证号码',
      trigger: 'blur'
    }
  ],
  ownerEidFrontUrl: [{required: true, message: '身份证正面图片地址不能为空', trigger: 'blur'}],
  ownerEidBackUrl: [{required: true, message: '身份证反面图片地址不能为空', trigger: 'blur'}],
  businessLicenseUrl: [{required: true, message: '营业执照图片地址不能为空', trigger: 'blur'}],
  categoryId: [{required: true, message: '主营类目不能为空', trigger: 'blur'}],
  countyCode: [{required: true, message: '省市区县不能为空', trigger: 'blur'}],
  detailAddress: [{required: true, message: '详细地址不能为空', trigger: 'blur'}]
})
const formRef = ref() // 表单 Ref
const categoryList = ref([])
const areaList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + (type || 'create'))
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ShopInfoApi.getShopInfo(id)
    } finally {
      formLoading.value = false
    }
  }
  categoryList.value = await ShopCategoryApi.getShopCategoryList({parentId: 0})
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CreateVO
    await ShopInfoApi.createShopInfo(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    type: undefined,
    name: undefined,
    logo: undefined,
    introduction: undefined,
    contactName: undefined,
    contactMobile: undefined,
    ownerEidNo: undefined,
    ownerEidFrontUrl: undefined,
    ownerEidBackUrl: undefined,
    businessLicenseUrl: undefined,
    countyCode: undefined,
    detailAddress: undefined
  }
  formRef.value?.resetFields()
}
</script>
